/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-4-17 下午1:50 Created by sky
 */
package com.jade.bss.base.customer.impl;

import java.util.Map;
import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.inject.Named;

import com.jade.bss.base.BssException;
import com.jade.bss.base.customer.CustomerConstants;
import com.jade.bss.base.customer.UserMapping;
import com.jade.bss.base.customer.UserMappingDao;
import com.jade.bss.base.customer.UserMappingManager;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户映射接口实现，采用UserMappingDao实现数据访问。
 *
 * @author sky
 * @version 1.0 13-4-17 下午1:50
 */
@Named ("bss_userMappingManager")
public class UserMappingManagerImpl
        implements UserMappingManager
{
    protected UserMappingDao mappingDao;

    @Inject
    public void setMappingDao(@Named ("bss_userMappingDao") UserMappingDao mappingDao)
    {
        this.mappingDao = mappingDao;
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Exception.class)
    public void addMapping(long customerId, String appCode, String userId)
            throws BssException
    {
        if (getUserId(customerId, appCode) != null) {
            //userId已经被绑定
            throw new BssException(CustomerConstants.ERR_CUSTOMER_BOUND, "you has bound a user", null, customerId,
                    appCode);
        }

        if (getCustomerId(appCode, userId) > 0) {
            //userId已经被绑定
            throw new BssException(CustomerConstants.ERR_USER_BOUND, "user has been bound", null, appCode, userId);
        }

        UserMapping mapping = new UserMapping(customerId, appCode);
        mapping.setUserId(userId);
        mappingDao.addMapping(mapping);
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Exception.class)
    public void removeMapping(long customerId, String appCode)
            throws BssException
    {
        mappingDao.removeMapping(customerId, appCode);
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Exception.class)
    public void removeMappings(long customerId)
            throws BssException
    {
        mappingDao.removeMapping(customerId);
    }

    public long getCustomerId(String appCode, String userId)
    {
        UserMapping mapping = mappingDao.getMapping(appCode, userId);
        if (mapping == null) {
            return -1;
        }
        else {
            return mapping.getCustomerId();
        }
    }

    public String getUserId(long customerId, String appCode)
    {
        UserMapping mapping = mappingDao.getMapping(customerId, appCode);
        if (mapping == null) {
            return null;
        }
        else {
            return mapping.getUserId();
        }
    }

    public Map<String, String> getMappings(long customerId)
    {
        return mappingDao.getUserMap(customerId);
    }
}

